<?php
/**
 * Ｍｃｒｐ暗号変換クラスモジュール
 */

class Mcrypt
{
	/** 区切り文字 */
	const SEPARATOR = '::';
	/** IV */
	protected $_iv;
	/** キー */
	protected $_sKey;

	public function __construct($sKey)
	{
		$this->_sKey = $sKey;
		$this->_iv = "";
	}

	public function setIv($iv)
	{
		$this->_iv = $iv;
	}

	public function getIv()
	{
		return base64_encode($this->_iv);
	}


	public function enc($data)
	{
	    $plain_text = $data;
	    $td  = mcrypt_module_open('des', '', 'ecb', '');
	    $key = substr($this->_sKey, 0, mcrypt_enc_get_key_size($td));
	    $iv  = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	    if (mcrypt_generic_init($td, $key, $iv) < 0) {
	        return FASLE;
	    }
	    $crypt_text = base64_encode(mcrypt_generic($td, $plain_text));
	    mcrypt_generic_deinit($td);
	    mcrypt_module_close($td);
	    return $crypt_text;
	}

	public function dec($data)
	{
	    $crypt_text = $data;
	    $td  = mcrypt_module_open('des', '', 'ecb', '');
	    $key = substr($this->_sKey, 0, mcrypt_enc_get_key_size($td));
	    $iv  = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	    if (mcrypt_generic_init($td, $key, $iv) < 0) {
	        return FALSE;
	    }
	    $plain_text = mdecrypt_generic($td, base64_decode($crypt_text));
	    mcrypt_generic_deinit($td);
	    mcrypt_module_close($td);
	    return $plain_text;
	}
}